<?
/**
 *订单记录类.
 *查询订单详情和处理订单的相关操作.
 */
class OrderRecord{
	/**
	 *订单号.
	 *var int 
	 */
	private $ordernum;
	
	/**
	 *票付通内部接口对象
	 *@var object
	 */
	private $s;
	
	/**
	 *键值数组对应UUstatus文本和样式
	 *@static
	 *@var array 
	 */
	public static $UUstatusT=array(0=>"未使用",1=>"<em class='green'>已使用</em>",2=>"已过期",3=>"<em class='red'>已取消</em>",4=>"被替代",5=>"被修改",6=>"已撤销",7=>"部分使用");
	
	/**
	 *键值数组对应UUstatus文本和样式
	 *@static
	 *@var array 
	 */
	public static $statusT=array("0"=>"未使用","1"=>"<em class='green'>已使用</em>","2"=>"<em class='gray'>已过期</em>","3"=>"<em class='red'>已取消</em>","4"=>"凭证码被替代","6"=>"被终端撤销</br><em class='red'>(已取消)</em>","5"=>"被终端修改</br><em class='green'>(已使用)</em>");
	
	/**
	 *键值数组对应UUpmode文本和样式
	 *@static
	 *@var array 
	 */
	public static $paymodeT=array(0=>"账户余额",1=>"支付宝",2=>"授信支付",3=>"产品自销");
	
	/**
	 *键值数组对应UUpaystatus文本和样式
	 *@static
	 *@var array 
	 */
	public static $paystatusT=array(1=>"<em class='green'>(已支付)</em>",2=>"<em class='orange'>(待支付)</em>");
	
	/**
	 *键值数组对应门票产品类型
	 *@static
	 *@var array 
	 */
	public static $p_typeT=array("A"=>"门票","B"=>"线路","C"=>"酒店","D"=>"商品","F"=>"套票");
	
	/**
	 *构造函数.
	 *@param int $ordernum 订单号
	 *@param object 票付通内部接口对象
	 */
	public function __construct($ordernum,$s){
		$this->ordernum=$ordernum;
		$this->s=$s;
	}
	
	/**
	 *格式化订单记录函数.
	 *联票订单将以存在主订单和从订单，非联票订单制存在主订单
	 *@param object simplexml对象
	 *@return array
	 */
	public static function format($simxml){
		$info=array();
		$info['childOrder']=array();
		$info['orderAlipay']=false;
		$info['orderCancel']=false;
		$info['orderAlter']=false;
		$count=count($simxml);
		foreach($simxml as $row){
			if($count>1){
				if($row->UUifpack>0){
					if($row->UUifpack==1){
						$info['mainOrder']=$row;
					}else{
						$info['packOrder'][]=$row;
						continue;
					}
				}else{
					if($row->UUconcat_id=="main"){
						$info['mainOrder']=$row;
					}else{
						$info['childOrder'][]=$row;
					}
				}
			}else{
				$info['mainOrder']=$row;
			}
			$info['totalPrice']+=(string)($row->UUtnum*$row->UUtprice);
			$info['totalTnum']+=(string)$row->UUtnum;
			$info['totalOrder']++;
		}
		if($info['mainOrder']->UUpmode==1&&$info['mainOrder']->UUpaystatus!=1){
			$info['orderAlipay']=true;
		}
		if($info['mainOrder']->UUremotenum==0&&(string)$info['mainOrder']->UUpaystatus==1){
			if(in_array((string)$info['mainOrder']->UUstatus,array(0))){
				$info['orderAlter']=true;
				$info['orderResend']=true;
			}
			if(in_array((string)$info['mainOrder']->UUstatus,array(0,2))){
				$info['orderCancel']=true;
			}
			
		}
		return $info;
	}
	/*订单操作（查看，修改，重发，取消,支付）权限*/
	
	/**
	 *订单操作权限查询函数.
	 *查看用户是否有订单操作权限
	 *@param int $order 订单号
	 *@param int $did 操作人ID
	 *@param int $account 普通用户账号，机预订手机号
	 *@param string $auth 需查询权限字段 orderView,orderCancel,orderAlter,orderChange
	 *@return array
	 */
	public static function orderOperAuth($order,$did,$account="",$auth){
		//if($order['mainOrder']->UUordernum=="100476") echo $auth;
		if($auth=="orderView"){
			if($did==(string)$order['mainOrder']->UUmid||$did==(string)$order['mainOrder']->UUaid||$did==1)
			return true;
		}
		if((string)$order['mainOrder']->UUordermode==0&&$order[$auth]){//分销下单权限
			if($did==(string)$order['mainOrder']->UUmid)
					return true;
		}
		if(in_array((string)$order['mainOrder']->UUordermode,array(1,2))&&$order[$auth]){//普通用户下单
			if($account==(string)$order['mainOrder']->UUordertel)
					return true;
		}
		return false;
	}
	
	/**
	 *查询订单数据.
	 *联票也一同被返回,故有可存在对个simplexml对象
	 *@return object
	 */
	public function info(){
		$ifpack=1;
		$xml=$this->s->Order_Globle_Search("","","","","","","","","","","","",$this->ordernum,"","","","","",1,1,0,999,0,$stype,$payinfo,$pmode,$remotenum,$origin,$p_type,$order_confirm,$aid,$concat,$ifpack);
		$simxml=simplexml_load_string($xml);
		return $this->format($simxml->Rec);
	}
	
	/**
	 *订单取消函数.
	 *联票也一同被返回,故有可存在对个simplexml对象
	 *@return bool 成功返回true
	 */
	public function cancel($operator){
		$orders=$this->info();
		$array=array();
		$array[]=$orders['mainOrder'];
		if($orders['mainOrder']->UUordermode==0){
			if($operator!=$orders['mainOrder']->UUmid) throw new Exception("非自身订单，无权取消");
		}else{
			$str="select account from pft_member where id=$operator";
			$GLOBALS['le']->query($str);
			$GLOBALS['le']->fetch_assoc();
			if($GLOBALS['le']->f("account")!=(string)$orders['mainOrder']->UUordertel)
				throw new Exception("非游客自身订单，无权取消");
		}
		$array=array_merge($array,$orders['childOrder']);
		foreach($array as $row){
			$this->s->Order_Change_Pro((string)$row->UUordernum,0,-1,0,$operator);
		}
		return true;
	}
	
	/**
	 *重发短信函数.
	 *@return bool 成功返回true
	 */
	public function resendMsg(){
		$orders=$this->info();
		return $this->s->reSend_SMS_Global_PL((string)$orders['mainOrder']->UUordernum,(string)$orders['mainOrder']->UUaid,(string)$orders['mainOrder']->UUmid);//最后重发短信
	}
	
	/**
	 *修改订单门票数函数.
	 *@param int $tid 门票ID
	 *@param int $tnum 门票数
	 *@param int $operator 操作人ID
	 *@return bool 成功返回true
	 */
	public function changeTnum($tid,$tnum,$operator){
		$orders=$this->info();
		$array=array();
		$array[]=$orders['mainOrder'];
		if($orders['mainOrder']->UUordermode==0){
			if($operator!=$orders['mainOrder']->UUmid) throw new Exception("非自身订单，无权修改数量");
		}else{
			$str="select account from pft_member where id=$operator";
			$GLOBALS['le']->query($str);
			$GLOBALS['le']->fetch_assoc();
			if($GLOBALS['le']->f("account")!=(string)$orders['mainOrder']->UUordertel)
				throw new Exception("非游客自身订单，无权修改数量");
		}
		$array=array_merge($array,$orders['childOrder']);
		foreach($array as $row){
			if((string)$row->UUtid==$tid&&$tnum<(string)$row->UUtnum){
				$totalprice=(float)$row->UUtprice*$tnum;
				$this->s->Order_Change_Pro((string)$row->UUordernum,$tnum,$totalprice,0,$operator);
			}
		}
		return true;
	}
	
	/**
	 *修改订单游玩时间函数.
	 *@param date $begintime 游玩时间
	 *@param int $operator 操作人ID
	 *@return bool 成功返回true
	 */
	public function changeBegintime($begintime,$operator){
		$orders=$this->info();
		$array[]=$orders['mainOrder'];
		if($orders['mainOrder']->UUordermode==0){
			if($operator!=$orders['mainOrder']->UUmid) throw new Exception("非自身订单，无权修改时间");
		}else{
			$str="select account from pft_member where id=$operator";
			$GLOBALS['le']->query($str);
			$GLOBALS['le']->fetch_assoc();
			if($GLOBALS['le']->f("account")!=(string)$orders['mainOrder']->UUordertel)
				throw new Exception("非游客自身订单，无权修改时间");
		}
		$times=strtotime($orders['mainOrder']->UUendtime-$UUbegintime);
		$array=array_merge($array,$orders['childOrder']);
		$endtime=date("Y-m-d H:i:s",strtotime($begintime)+$times);
		foreach($array as $row){
			$this->s->Order_Change_Pro((string)$row->UUordernum,-1,-1,1,$operator,$begintime,$endtime);
		}
		return true;
	}

	/**
	 *未支付订单支付函数.
	 *将处理订单的分润数据，并跳的支付宝支付
	 */
	public function alipay(){
		$orderInfo=$this->info();
		$orderid=(string)$orderInfo['mainOrder']->UUordernum;
		$title=($orderInfo['mainOrder']->UUltitle).($orderInfo['mainOrder']->UUttitle);
		$money=$orderInfo['totalPrice']/100;
		$url="http://www.12301.cc/scenicDetail.html?lid=".$orderInfo['mainOrder']->UUlid;
		
		$mid=(string)$orderInfo['mainOrder']->UUmid;
		$str="select alipay from pft_member where id=$mid";
		$GLOBALS['le']->query($str);
		$GLOBALS['le']->fetch_assoc();
		$alicount=$GLOBALS['le']->f("alipay");
		$describe="分销商预订".$title;
		
		$apply_did=(string)$orderInfo['mainOrder']->UUaid;
		$str="select alipay,fee_bank from pft_member where id=$apply_did";
		$GLOBALS['le']->query($str);
		$GLOBALS['le']->fetch_assoc();
		$fee_bank=$GLOBALS['le']->f("fee_bank")/1000;
		
		$acount1=$GLOBALS['le']->f("alipay");
		$money1 = $orderInfo['totalPrice']*(1-$fee_bank);
		$clearDesc1="供应商".$title ."(".$orderid.")分润";
		$acount2="";
		$money2="";
		$clearDesc2="";
		if($orderInfo['mainOrder']->UUordermode==1
            &&(string)$orderInfo['mainOrder']->UUmid!=(string)$orderInfo['mainOrder']->UUaid){//普通用户下单
			$mid=(string)$orderInfo['mainOrder']->UUmid;
			$str="select alipay from pft_member where id=$mid";
			$GLOBALS['le']->query($str);
			$GLOBALS['le']->fetch_assoc();
			$acount2=$GLOBALS['le']->f("alipay");
			$money2=0;
			$clearDesc2="分销商".$title ."(".$orderid.")分润";
			/*分销商利润*/
			$orders=array(0=>$orderInfo['mainOrder']);
			$orders=array_merge($orders,$orderInfo['childOrder']);
			foreach($orders as $row){
				$mid=(string)$row->UUmid;
				$pid=(string)$row->UUpid;
				$pro=new ProductInfo($pid,$this->s);
				//分销权限判定
				if(!$pro->supply($mid)) return false;
				if((string)$row->UUaprice==0) return false;
				$dprice = $pro->dprice($mid);
				$money2 += ((string)$row->UUtprice-(string)$row->UUaprice-$dprice)*(string)$row->UUtnum;
			}
			/*供应商利润*/
			$money1=($money1-$money2);
		}
		
		$a_key[]='WIDout_trade_no';
		$a_key[]='WIDsubject';
		$a_key[]='WIDtotal_fee';
		$a_key[]='WIDbody';
		$a_key[]='WIDshow_url';
		$a_key[]='WIDbuyer';
		
		$a_key[]='WIDaccount1';
		$a_key[]='WIDpay1';
		$a_key[]='WIDpay1txt';
		$a_key[]='WIDaccount2';
		$a_key[]='WIDpay2';
		$a_key[]='WIDpay2txt';
		
		$a_key[]='return_url';
		$a_key[]='notify_url';
		
		$a_value[]=$orderid;//商户订单号,商户网站订单系统中唯一订单号，必填
		$a_value[]=$title;//订单名称或产品名称，必填
		$a_value[]=$money;//付款金额，必填
		$a_value[]=$describe;//订单描述
		$a_value[]=$url;//产品展示路径 例如：http://www.12301.cc/s_01.html
		$a_value[]=$alicount;//买家绑定的支付宝帐号 最好填上

		$a_value[]=$acount1;//分润帐号1
		$a_value[]=$money1;//分润1金额 分单位
		$a_value[]=$clearDesc1;//分润1描述
		$a_value[]=$acount2;//分润帐号2
		$a_value[]=$money2;//分润2金额 分单位
		$a_value[]=$clearDesc2;//分润2描述
		
		$a_value[]="http://www.12301.cc/alipay/ali_order/return_url.php";
		$a_value[]="http://www.12301.cc/alipay/ali_order/notify_url.php";
		/*print_r(array_combine($a_key,$a_value));
		exit;*/
		$this->make_post($a_key,$a_value);
	}
	
	/**
	 *未支付订单支付提交函数.
	 *@uses OrderRecord::alipay
	 */
	public static function make_post($id, $vid){
		$post_data = array();
		if (!is_array($id) && !is_array($vid)){
		$post_data[$id] = $vid; 
		}else{
            $post_data = array_combine($id, $vid);
//		foreach ($id as $kk=>$vv){
//		$post_data[$vv]=$vid[$kk];
//		}
		}
		$url='http://pay.12301.cc/alipayapi.php'; 
//		$o ="";
        $post_data = http_build_query($post_data);

//		foreach ($post_data as $k=>$v){
//		$o.= "$k=".urlencode($v)."&";
//		}
//		$post_data=substr($o,0,-1);
		$ch = curl_init(); 
		curl_setopt($ch, CURLOPT_POST, 1); 
		curl_setopt($ch, CURLOPT_HEADER, 0); 
		curl_setopt($ch, CURLOPT_URL,$url); 
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,0);
		return curl_exec($ch);
	}

    /**
     * 使用IPS支付
     *
     * @return bool
     */
    public function ipsPay()
    {
        $orderInfo = $this->payCommon();
        $payDate   = date('Ymd');
        $Amount = number_format($orderInfo['money'], 2, '.', '');
        //IPS证书
        $key = '7667659191929397103470329788807862402627565924638280479623896'.
          '0393156885586815305050516493889730425518949732797083380078766300585';
        $sign      = 'billno'.$orderInfo['orderid'].'currencytypeRMBamount'
            .$Amount.'date'.$payDate.'orderencodetype5'.$key;
        $signMd5   = md5($sign);
        $Bankco = $_REQUEST['Bankco'];
        $payParams = array(
            'Mer_code'  => '026188',
            'Billno'    => $orderInfo['orderid'],
            'Amount'    => $Amount,
            'Date'      => $payDate,
            'Currency_Type' => 'RMB',
            'Gateway_Type'  => '01',
            'Lang'      => 'GB',
            'Merchanturl'   => 'http://www.12301.cc/ips/ips_return_url.php',
            'FailUrl'   => '',
            'ErrorUrl'  => '',
            'Attach'    => '支付订单'.$orderInfo['orderid'],//商户数据包
            'DispAmount'    => '',
            'OrderEncodeType'   => 5,//订单支付接口加密方式
            'RetEncodeType' => 17,
            'Rettype'   => 1,
            'ServerUrl' => 'http://www.12301.cc/ips/ips_notify_url.php',
            'SignMD5'   => $signMd5,
            'DoCredit'  => 1,
            'Bankco'    => $Bankco,
        );

        echo $this->buildPayForm('https://pay.ips.com.cn/ipayment.aspx', $payParams);
        return true;
    }

    /**
     * 构建支付表单
     *
     * @param string $url 提交地址
     * @param array $data  提交的数据
     * @return mixed
     */
    public function buildPayForm($url, Array $data)
    {
        $html = <<<HTML
<html>
  <head>
    <title>跳转......</title>
    <meta http-equiv="content-Type" content="text/html; charset=utf-8" />
  </head>
  <body>
   <form action="{$url}" method="post" id="frm1">
   {inputField}
   </form>
   <script language="javascript">
      document.getElementById("frm1").submit();
    </script>
  </body>
</html>
HTML;
        $inputField = '';
        foreach($data as $key=>$val) {
            $inputField .= "<input type='hidden' name='{$key}' value='{$val}'/>";
        }
        return str_replace('{inputField}', $inputField, $html);
    }

    /**
     * 订单数据
     *
     * @return array|bool
     */
    public function payCommon()
    {
        $orderInfo=$this->info();
        $orderid=(string)$orderInfo['mainOrder']->UUordernum;
        $title=($orderInfo['mainOrder']->UUltitle).($orderInfo['mainOrder']->UUttitle);
        $money=$orderInfo['totalPrice']/100;
        $url="http://www.12301.cc/scenicDetail.html?lid=".$orderInfo['mainOrder']->UUlid;

        $mid=(string)$orderInfo['mainOrder']->UUmid;
        $str="select alipay from pft_member where id=$mid";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $alicount=$GLOBALS['le']->f("alipay");
        $describe="分销商预订".$title;

        /*****分润1******/
        $apply_did=(string)$orderInfo['mainOrder']->UUaid;
        $str="select alipay,fee_bank from pft_member where id=$apply_did";
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $fee_bank=$GLOBALS['le']->f("fee_bank")/1000;
//            $acount1=$GLOBALS['le']->f("alipay");
        $money1 = $orderInfo['totalPrice']*(1-$fee_bank);//对应$apply_did

        $clearDesc1 = "供应商".$title ."(".$orderid.")分润";
        $money2     = 0;
        $clearDesc2 = "";
        if($orderInfo['mainOrder']->UUordermode==1
            &&(int)$orderInfo['mainOrder']->UUmid!=(int)$orderInfo['mainOrder']->UUaid){//普通用户下单

            $money2=0; //对应(int)$orderInfo['mainOrder']->UUmid
            $clearDesc2="分销商" . $title ."(".$orderid.")分润";
            /*分销商利润*/
            $orders=array(0=>$orderInfo['mainOrder']);
            $orders=array_merge($orders, $orderInfo['childOrder']);
            foreach ($orders as $row){
                $mid = (int)$row->UUmid;
                $pid = (int)$row->UUpid;
                $pro = new ProductInfo($this->s, $pid);
                //分销权限判定
                if(!$pro->supply($mid)) return false;
                if((float)$row->UUaprice==0) return false;
                $dprice = $pro->dprice($mid);
                $money2 += ($row->UUtprice - $row->UUaprice - $dprice) * (int)$row->UUtnum;
            }
            /*供应商利润*/
            $money1     = ($money1-$money2);
        }
        //TODO:供应商分润
        $royalty_parameters = "$apply_did^$money1^$clearDesc1";
        //TODO:散客购买，分销商分润
        if($money2>0) {
            $mid2 = (int)$orderInfo['mainOrder']->UUmid;
            $royalty_parameters .= "|$mid2^$money2^$clearDesc2";
        }
        //TODO:支付记录,先判断是否存在记录
        $sql_chk = "SELECT id FROM pft_ips_rec WHERE out_trade_no='{$orderid}'";
        $GLOBALS['le']->query($sql_chk);
        $res = $GLOBALS['le']->fetch_assoc();
        if(!$res['id']) {
            $sql_log_ips = "INSERT INTO pft_ips_rec(fid,royalty_parameters,".
                " total_fee, out_trade_no,subject) VALUES($mid,'$royalty_parameters',".
                "{$orderInfo['totalPrice']},'$orderid','$describe')";
            $GLOBALS['le']->query($sql_log_ips);
        }

        return compact('orderid', 'title', 'money', 'describe', 'url',
            'alicount', 'acount1', 'money1', 'clearDesc1', 'acount2',
            'money2', 'clearDesc2');
    }
}
?>